// 分类模块
import { topCategory } from '@/api/constants'
import { getAllCategoryAPI } from '@/api/category'

export default {
  namespaced: true,
  state () {
    return {
      list: topCategory.map(item => ({ name: item }))
    }
  },

  // 同步操作
  mutations: {
    // 加载成功后要替换list中的分类，防止前后端数据不一样
    setCategory (state, headCategory) {
      state.list = headCategory
    },
    // 修改当前一级分类下的open为true，
    show (state, item) {
      const category = state.list.find(category => category.id === item.id)
      category.open = true
    },
    // 修改当前一级分类下的open为false，
    hide (state, item) {
      const category = state.list.find(category => category.id === item.id)
      category.open = false
    }
  },

  // 异步操作在actions中执行
  actions: {
    async getList ({ commit }) {
      const { result } = await getAllCategoryAPI()
      result.forEach(item => {
        item.open = false
      })
      // console.log(result)
      commit('setCategory', result)
    }
  }
}
